package com.tnsw.noxnox;

import java.util.Set;

import org.json.JSONObject;

import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.http.THttpBase;
import com.tnsw.noxnox.downloader.DLBase;
import com.tnsw.noxnox.downloader.DLInterface;
import com.tnsw.noxnox.downloader.DailyMotionDL;
import com.tnsw.noxnox.downloader.GCMManagerService;
import com.tnsw.noxnox.downloader.GCMReceiverInterface;
import com.tnsw.noxnox.downloader.YoutubeDL;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class YoutubeTest extends Activity implements OnClickListener, DLInterface, Runnable, GCMReceiverInterface {

	private String tag = "YoutubeTest";
	private Button btnLoad, btnStop, btnPause, btnDailyMotion;
	private TextView txtUrl, lblStatus;
	private ProgressBar progressBar1;
	
	private DLBase dl;
	private AsyncManager asyncManager;
	
	public YoutubeTest() {
		Log.d(tag, "Constructor()");
		this.asyncManager = AsyncManager.getInstance();
		
		GCMManagerService gcms = GCMManagerService.getInstance();
		gcms.registerReceiver(this);
				
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_youtube_test);
		View v = this.getWindow().getDecorView().getRootView();
		Log.d(tag, "view=" + v.toString());
		
		this.btnLoad = (Button) this.findViewById(R.id.btnLoad);
		this.btnLoad.setOnClickListener(this);
		
		this.btnStop = (Button) this.findViewById(R.id.btnStop);
		this.btnStop.setOnClickListener(this);
		this.btnStop.setVisibility(View.INVISIBLE);
		
		this.btnPause = (Button) this.findViewById(R.id.btnPause);
		this.btnPause.setOnClickListener(this);
		this.btnPause.setVisibility(View.INVISIBLE);
		
		this.btnDailyMotion = (Button) this.findViewById(R.id.btnDailyMotion);
		this.btnDailyMotion.setOnClickListener(this);
		
		this.txtUrl = (TextView) this.findViewById(R.id.txtUrl);
		
		this.progressBar1 = (ProgressBar) this.findViewById(R.id.progressBar1);
		this.lblStatus = (TextView) this.findViewById(R.id.lblStatus);
		
		Log.d(tag, "onCreated()");
		
		Intent intent = this.getIntent();
		if (intent != null) {
			if (intent.getAction() != null) {
				if (intent.getAction().equals(Intent.ACTION_SEND)) {
					this.handleShareIntent(intent);
				}		
			}
			
		}
		
		//this.getActionBar().show();
		this.getActionBar().setDisplayHomeAsUpEnabled(true);
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.d(tag, "Click something on the actionbar");
		switch (item.getItemId()) {
			case android.R.id.home:
				Intent parent = new Intent(this, com.tnsw.noxnox.MainActivity.class);
				this.startActivity(parent);
				this.finish();
				break;
		}
		return(true);
	}
	
	private void handleShareIntent(Intent intent) {
		String youtubeUrl = this.findYoutubeUrl(intent);
		if (youtubeUrl.equals("") ==  false) {
			this.txtUrl.setText(youtubeUrl);
			String url = this.txtUrl.getText().toString();
			this.dl = new YoutubeDL(this, url);
			this.dl.setDLInterface(this);
			this.dl.doit();
		}
	}
	
	private String findYoutubeUrl(Intent intent) {
		if (intent == null) { return(""); }
		
		String ss = "";
		
		Bundle extras = intent.getExtras();
		
		Set<String> set = extras.keySet();
		for (String s : set) {
			//Log.d(tag, "key=" + s + ", values=" + extras.get(s).toString());
			if (s.equals("android.intent.extra.TEXT")) {
				String value = extras.getString(s);
				String host = THttpBase.getHost(value);
				if (host.equals("www.youtube.com") || (host.equals("m.youtube.com")) ) {
					ss = value;
					
					break;
				}
			}
			
		}
		
		return(ss);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.youtube_test, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		if (v == this.btnLoad) {
			//String urlx = "http://www.youtube.com/watch?v=9bZkp7q19f0";
			//urlx = "http://www.youtube.com/watch?annotation_id=annotation_57484&feature=iv&src_vid=mfxDgbPk_QA&v=q7EQbpcOPPM";
			//urlx = "http://www.youtube.com/watch?v=NKE-RXR_XIs&feature=youtube_gdata_player";
			//this.txtUrl.setText(urlx);
			String url = this.txtUrl.getText().toString();
			if (url.equals("")) {
				url = "http://www.youtube.com/watch?v=9bZkp7q19f0";
			}
			
			Log.d(tag, "downloading URL: " + url);
			
			this.dl = new YoutubeDL(this, url);
			this.dl.setDLInterface(this);
			this.dl.doit();
			
		} else if (v == this.btnDailyMotion) {
			//http://www.dailymotion.com/video/xh0va3_sex-is-zero_sexy#.UTZAy3yPhJE
			//http://www.dailymotion.com/en/relevance/search/natalie+korea/1#video=xg3szz
			String url = this.txtUrl.getText().toString();
			//this.txtUrl.setText("http://www.dailymotion.com/video/x4z9f2_nude-beach-004_sexy#.UTgHyHyPhJE");
			
			if (url.equals("")) {
				url = "http://www.dailymotion.com/video/xh0va3_sex-is-zero_sexy#.UTZAy3yPhJE";
			}
			
			this.dl = new DailyMotionDL(this, url);
			this.dl.setDLInterface(this);
			this.dl.doit();
			
		} else if (v == this.btnPause) {
			if (this.dl.getCurrentHttpBase() != null) {
				if (this.dl.isPaused() == true) {
					this.dl.resume();
					this.btnPause.setText("Pause");
				} else {
					this.dl.pause();
					this.btnPause.setText("Resume");
				}
			}
			
		}
		
	}

	@Override
	public void onProgressUI(DLBase sender) {
		this.progressBar1.setMax((int) sender.getMax());
		this.progressBar1.setProgress(sender.getCurrentPosition());
		
		this.lblStatus.setText(sender.getTextStatus());
		
	}

	@Override
	public void onProgressBG(DLBase sender) {
		
	}

	@Override
	public void onCompletedUI(DLBase sender, long result) {
		this.lblStatus.setText(sender.getTextStatus());
		if (result == 0) {
			this.btnPause.setVisibility(View.INVISIBLE);
			this.btnStop.setVisibility(View.INVISIBLE);
		}
		
	}

	@Override
	public void run() {
		
	}

	@Override
	public void onStartedBG(DLBase sender) {
		this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				btnPause.setVisibility(View.VISIBLE);
				btnStop.setVisibility(View.VISIBLE);
				
			}
		});
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.d(tag, "onStart()");
	}
    
	@Override
    protected void onRestart() {
		super.onRestart();
		Log.d(tag, "onRestart()");
	}

	@Override
    protected void onResume() {
		super.onResume();
		Log.d(tag, "onResume()");
	}

	@Override
    protected void onPause() {
		super.onPause();
		Log.d(tag, "onPause()");
	}

	@Override
    protected void onStop() {
		super.onStop();
		Log.d(tag, "onStop()");
	}

	@Override
    protected void onDestroy() {
		super.onDestroy();
		Log.d(tag, "onDestroy()");
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
	@Override
	protected void onRestoreInstanceState (Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		Log.d(tag, "onRestoreInstanceState()");
	}
	
	@Override
	protected void onSaveInstanceState (Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d(tag, "onSaveInstanceState()");
		
	}

	@Override
	public void onReceiveMessage(Intent intent) {
		Log.d(tag, "Yes, I got message");
		
		Bundle b = intent.getExtras();
		if (b.containsKey("value")) {
			String url = b.getString("value");
			
			this.txtUrl.setText(url);
		}
	}

	@Override
	public void onError(DLBase sender, boolean isBackground, String message, Exception e) {
		
	}
	
}
